/*
 * game-kernel.cpp
 *
 *  Created on: 10.11.2012
 *      Author: caffeine
 */




#include "StaticModelObject.h"
#include "FileLoader.h"

#include <xml/IFactoryEnvironment.h>
#include <xml/IFactoryRecord.h>
#include <xml/IXmlNode.h>
#include <log/Log.h>
#include <object/WorldElement.h>

class StaticModelRecord:public irr::xml::IFactoryRecord{
	virtual irr::xml::TagResult tagHandlerBefor(irr::xml::IFactoryEnvironment*environment,irr::xml::IXmlNode*node){
		LOG("Create static decor...");

		irr::io::path href=environment->getDevice()->getFileSystem()->getAbsolutePath(node->getAttString("href"));
		LOG("href=%s",href.c_str());
		irr::object::ContainerNodeObject*parent=0;
		if (node->getParent() && node->getParent()->getTag())
			parent=(irr::object::ContainerNodeObject*)node->getParent()->getTag();
		StaticModelObject*model=new StaticModelObject(href,node,parent,environment->getDevice());
		irr::object::WorldElement*obj=new irr::object::WorldElement(environment->getDevice()->getSceneManager(),parent,true);
		obj->setRadiusObjectSize(node->getAttF32("radius",10));
		obj->setModel(model);
		model->drop();
		node->setTag(obj);
		return irr::xml::NEXT;
	}

	virtual irr::core::array<irr::core::stringc> getProcessedTags(){
		irr::core::array<irr::core::stringc> res;
		res.push_back("decor:static");
		return res;
	};
};

void regStaticModel(irr::xml::IFactoryEnvironment*environment){
	StaticModelRecord*temp=new StaticModelRecord();
	environment->registerHandler(temp);
	temp->drop();
}

StaticModelObject::StaticModelObject(irr::io::path model,irr::xml::IXmlNode*e,irr::object::ContainerNodeObject*container,irr::IrrlichtDevice*device):irr::object::ModelObject(container,device),irr::ILoadableObject(device){
	path=model;
	elements=e;
	if (elements)
		elements->grab();
}

StaticModelObject::~StaticModelObject(){
	if (elements)
		elements->drop();
}

void StaticModelObject::on_model_load(irr::scene::ISceneNode*parent){
	node=FileLoader::getNode(path,parent);
	node->grab();
	for (irr::u32 i=0;i<elements->getNodeCount();i++)
		getDevice()->getFactoryEnvironment()->runNode(elements->getNode(i));
}

void StaticModelObject::on_model_unload(){
	getContainer()->removeAllChild();
	node->drop();
	node->remove();
}
